using Microsoft.AspNetCore.Mvc;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// UUM用户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UumUserController : ControllerBase
    {
        private readonly IUumUserService _uumUserService;
        private readonly ILogger<UumUserController> _logger;

        public UumUserController(
            IUumUserService uumUserService,
            ILogger<UumUserController> logger)
        {
            _uumUserService = uumUserService;
            _logger = logger;
        }

        /// <summary>
        /// 根据用户名查询UUM用户信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>用户信息</returns>
        [HttpGet("by-username/{userName}")]
        public async Task<ActionResult<UumUserQueryResponse>> GetUserByUserName(
            [Required] string userName)
        {
            try
            {
                _logger.LogInformation("开始查询UUM用户信息: UserName={UserName}", userName);
                
                var result = await _uumUserService.GetUserByUserNameAsync(userName);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户信息成功: UserName={UserName}", userName);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户信息失败: UserName={UserName}, Message={Message}", userName, result.Message);
                    return NotFound(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户信息时发生异常: UserName={UserName}", userName);
                return StatusCode(500, new UumUserQueryResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据用户ID查询UUM用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户信息</returns>
        [HttpGet("by-id/{userId:int}")]
        public async Task<ActionResult<UumUserQueryResponse>> GetUserById(
            [Required] int userId)
        {
            try
            {
                _logger.LogInformation("开始查询UUM用户信息: UserId={UserId}", userId);
                
                var result = await _uumUserService.GetUserByIdAsync(userId);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户信息成功: UserId={UserId}", userId);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户信息失败: UserId={UserId}, Message={Message}", userId, result.Message);
                    return NotFound(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户信息时发生异常: UserId={UserId}", userId);
                return StatusCode(500, new UumUserQueryResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据工号查询UUM用户信息
        /// </summary>
        /// <param name="peopleIdentifier">工号</param>
        /// <returns>用户信息</returns>
        [HttpGet("by-people-identifier/{peopleIdentifier}")]
        public async Task<ActionResult<UumUserQueryResponse>> GetUserByPeopleIdentifier(
            [Required] string peopleIdentifier)
        {
            try
            {
                _logger.LogInformation("开始查询UUM用户信息: PeopleIdentifier={PeopleIdentifier}", peopleIdentifier);
                
                var result = await _uumUserService.GetUserByPeopleIdentifierAsync(peopleIdentifier);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户信息成功: PeopleIdentifier={PeopleIdentifier}", peopleIdentifier);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户信息失败: PeopleIdentifier={PeopleIdentifier}, Message={Message}", peopleIdentifier, result.Message);
                    return NotFound(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户信息时发生异常: PeopleIdentifier={PeopleIdentifier}", peopleIdentifier);
                return StatusCode(500, new UumUserQueryResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 检查用户名是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>是否存在</returns>
        [HttpGet("exists/{userName}")]
        public async Task<ActionResult<object>> CheckUserNameExists(
            [Required] string userName)
        {
            try
            {
                _logger.LogInformation("开始检查UUM用户名是否存在: UserName={UserName}", userName);
                
                var exists = await _uumUserService.UserNameExistsAsync(userName);
                
                _logger.LogInformation("检查UUM用户名是否存在完成: UserName={UserName}, Exists={Exists}", userName, exists);
                
                return Ok(new
                {
                    success = true,
                    message = "检查完成",
                    data = new
                    {
                        userName = userName,
                        exists = exists
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查UUM用户名是否存在时发生异常: UserName={UserName}", userName);
                return StatusCode(500, new
                {
                    success = false,
                    message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 通过POST方式根据用户名查询UUM用户信息
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>用户信息</returns>
        [HttpPost("query")]
        public async Task<ActionResult<UumUserQueryResponse>> QueryUserByUserName(
            [FromBody] UumUserQueryRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.UserName))
                {
                    return BadRequest(new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "请求参数无效，用户名不能为空"
                    });
                }

                _logger.LogInformation("开始查询UUM用户信息: UserName={UserName}", request.UserName);
                
                var result = await _uumUserService.GetUserByUserNameAsync(request.UserName);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户信息成功: UserName={UserName}", request.UserName);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户信息失败: UserName={UserName}, Message={Message}", request.UserName, result.Message);
                    return NotFound(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户信息时发生异常: UserName={UserName}", request?.UserName);
                return StatusCode(500, new UumUserQueryResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据用户名更新用户电话
        /// </summary>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPost("update-phone")]
        public async Task<ActionResult<UpdateUserPhoneResponse>> UpdateUserPhone(
            [FromBody] UpdateUserPhoneRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.UserName))
                {
                    return BadRequest(new UpdateUserPhoneResponse
                    {
                        Success = false,
                        Message = "请求参数无效，用户名不能为空"
                    });
                }

                _logger.LogInformation("开始更新UUM用户电话: UserName={UserName}, UserPhone={UserPhone}", request.UserName, request.UserPhone);
                
                var result = await _uumUserService.UpdateUserPhoneAsync(request.UserName, request.UserPhone);
                
                if (result.Success)
                {
                    _logger.LogInformation("更新UUM用户电话成功: UserName={UserName}", request.UserName);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("更新UUM用户电话失败: UserName={UserName}, Message={Message}", request.UserName, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新UUM用户电话时发生异常: UserName={UserName}", request?.UserName);
                return StatusCode(500, new UpdateUserPhoneResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据用户名查询用户电话
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>用户电话</returns>
        [HttpPost("get-phone")]
        public async Task<ActionResult<GetUserPhoneResponse>> GetUserPhone(
            [FromBody] GetUserPhoneRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.UserName))
                {
                    return BadRequest(new GetUserPhoneResponse
                    {
                        Success = false,
                        Message = "请求参数无效，用户名不能为空"
                    });
                }

                _logger.LogInformation("开始查询UUM用户电话: UserName={UserName}", request.UserName);
                
                var result = await _uumUserService.GetUserPhoneAsync(request.UserName);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户电话成功: UserName={UserName}", request.UserName);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户电话失败: UserName={UserName}, Message={Message}", request.UserName, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户电话时发生异常: UserName={UserName}", request?.UserName);
                return StatusCode(500, new GetUserPhoneResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据用户名更新退费任务数量
        /// </summary>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPost("update-task-amount")]
        public async Task<ActionResult<UpdateTaskAmountResponse>> UpdateTaskAmount(
            [FromBody] UpdateTaskAmountRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.UserName))
                {
                    return BadRequest(new UpdateTaskAmountResponse
                    {
                        Success = false,
                        Message = "请求参数无效，用户名不能为空"
                    });
                }

                _logger.LogInformation("开始更新UUM用户退费任务数量: UserName={UserName}, TaskAmount={TaskAmount}", request.UserName, request.TaskAmount);
                
                var result = await _uumUserService.UpdateTaskAmountAsync(request.UserName, request.TaskAmount);
                
                if (result.Success)
                {
                    _logger.LogInformation("更新UUM用户退费任务数量成功: UserName={UserName}, TaskAmount={TaskAmount}", request.UserName, request.TaskAmount);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("更新UUM用户退费任务数量失败: UserName={UserName}, TaskAmount={TaskAmount}, Message={Message}", request.UserName, request.TaskAmount, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新UUM用户退费任务数量时发生异常: UserName={UserName}, TaskAmount={TaskAmount}", request?.UserName, request?.TaskAmount);
                return StatusCode(500, new UpdateTaskAmountResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 根据用户名查询退费任务数量
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>退费任务数量</returns>
        [HttpPost("get-task-amount")]
        public async Task<ActionResult<GetTaskAmountResponse>> GetTaskAmount(
            [FromBody] GetTaskAmountRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.UserName))
                {
                    return BadRequest(new GetTaskAmountResponse
                    {
                        Success = false,
                        Message = "请求参数无效，用户名不能为空"
                    });
                }

                _logger.LogInformation("开始查询UUM用户退费任务数量: UserName={UserName}", request.UserName);
                
                var result = await _uumUserService.GetTaskAmountAsync(request.UserName);
                
                if (result.Success)
                {
                    _logger.LogInformation("查询UUM用户退费任务数量成功: UserName={UserName}, TaskAmount={TaskAmount}", request.UserName, result.TaskAmount);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询UUM用户退费任务数量失败: UserName={UserName}, Message={Message}", request.UserName, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询UUM用户退费任务数量时发生异常: UserName={UserName}", request?.UserName);
                return StatusCode(500, new GetTaskAmountResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 批量更新授权码：将id_no字段不为空的数据，截取id_no的后四位，加上@再加上user_name，存入auth_code字段
        /// </summary>
        /// <returns>批量更新结果</returns>
        [HttpPost("batch-update-auth-code")]
        public async Task<ActionResult<BatchUpdateAuthCodeResponse>> BatchUpdateAuthCode()
        {
            try
            {
                _logger.LogInformation("开始批量更新UUM用户授权码");
                
                var result = await _uumUserService.BatchUpdateAuthCodeAsync();
                
                if (result.Success)
                {
                    _logger.LogInformation("批量更新UUM用户授权码成功: UpdatedCount={UpdatedCount}, TotalCount={TotalCount}", result.UpdatedCount, result.TotalCount);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("批量更新UUM用户授权码失败: Message={Message}", result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量更新UUM用户授权码时发生异常");
                return StatusCode(500, new BatchUpdateAuthCodeResponse
                {
                    Success = false,
                    Message = "服务器内部错误",
                    UpdatedCount = 0,
                    TotalCount = 0
                });
            }
        }
    }
}